using System;
using System.IO;

namespace SpoonFilesystem
{
	public class FileHeader : IComparable<FileHeader>
	{
		public const int HeaderSize = 28;
		public const int BlockSize = 512;

		private ulong _id;
		private DateTime _changeTime = DateTime.Now;
		private DateTime _readTime = DateTime.Now;
		private byte[] _data = new byte[0];

		private bool _changed = false;

		public FileHeader(ulong id)
		{
			_id = id;
		}

		internal FileHeader(BinaryReader br)
		{
			_id = br.ReadUInt64();
			_changeTime = new DateTime(br.ReadInt64());
			_readTime = new DateTime(br.ReadInt64());

			int length = br.ReadInt32();
			_data = br.ReadBytes(length);
		}

		internal void Write(BinaryWriter bw)
		{
			bw.Write(Id);
			bw.Write(ChangeTime.Ticks);
			bw.Write(ReadTime.Ticks);
			bw.Write(_data.Length);

			byte[] buffer = new byte[BlockSize];
			Array.Copy(_data, buffer, _data.Length);
			bw.Write(buffer);
		}

		public ulong Id
		{
			get { return _id; }
		}

		public DateTime ChangeTime
		{
			get { return _changeTime; }
		}

		public DateTime ReadTime
		{
			get { return _readTime; }
		}

		public int Length
		{
			get { return _data.Length; }
		}

		public byte[] Data
		{
			get
			{
				_readTime = DateTime.Now;
				_changed = true;
				return _data;
			}
			set
			{
				_changed = true;
				_data = value;
			}
		}

		public bool Changed
		{
			get { return _changed; }
			set { _changed = value; }
		}

		public int CompareTo(FileHeader other)
		{
			return _readTime.CompareTo(other._readTime);
		}
	}
}